<template>
    <div>
    <el-container>
      <el-main>
        <el-scrollbar>
          <el-row>
            <el-col>
              <el-text>商品名称</el-text>
              <el-input v-model="serch.GoodsName" style="width: 100px;" clearable></el-input>
              <el-text>生产批次</el-text>
              <el-input v-model="serch.Productionbatches" style="width: 100px;" clearable></el-input>
              <el-text>保质期（天）</el-text>
              <el-input v-model="serch.ShelflifeDay" style="width: 100px;" clearable></el-input>
              <el-text>生产许可证</el-text>
              <el-input v-model="serch.Productionlicense" style="width: 100px;" clearable></el-input>
              <el-text>生产企业</el-text>
              <el-input v-model="serch.ProductionCompany" style="width: 100px;" clearable></el-input>
              <el-button type="primary"  @click="gettrace">查询</el-button>
            </el-col>
          </el-row>
            <el-button type="primary" :icon="Plus" @click="AddTrace">新增</el-button>
            <el-button type="primary" :icon="Delete">删除</el-button>
            <span style="margin-right: 550px;"></span>
            <el-icon><RefreshRight /></el-icon>
            <el-icon><Setting /></el-icon>
            <el-icon><Filter /></el-icon>
            <el-table
    ref="multipleTableRef"
    :data="tableData"
    style="width: 100%"
    @selection-change="handleSelectionChange"
  >
  <el-table-column type="selection" :selectable="selectable" width="55" />
            <el-table-column type="index" label="序号" width="160" />
            <el-table-column prop="goodsName" label="商品名称" width="160" />
            <el-table-column prop="productionbatches" label="生产批次" width="160" />
            <el-table-column prop="shelflifeDay" label="保质期（天）" width="160" />
            <el-table-column prop="productionlicense" label="生产许可证号" width="160" />
            <el-table-column prop="productionCompany" label="生产企业" width="210" />
            <el-table-column  label="操作" width="180" >
                <template #default="{row}">
                    <el-link type="primary" style="color:purple;" @click="handMing(row.trId)">详情</el-link>
                    <el-link type="primary" @click="handupdatetraceable(row.trId)">修改</el-link>
                    <el-link type="primary">导出溯源码</el-link>
                    <el-link type="primary" @click="handdeltraceId(row.trId)">删除</el-link>
                </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </el-main>
    </el-container>
    </div>
    <!--新增-->
    <el-dialog v-model="dialoginsertFormVisible" title="新增溯源" width="500">
    <el-form :model="insertform">
      <el-form-item label="商品名称" :label-width="100">
        <el-select
      v-model="insertform.goodsId"
      placeholder="请选择"
    >
      <el-option
        v-for="item in goodsData"
        :key="item.goodsId"
        :label="item.goodsName"
        :value="item.goodsId"
      />
    </el-select>
      </el-form-item>
      <el-form-item label="生产批次" :label-width="100">
        <el-input v-model="insertform.productionbatches" clearable />
      </el-form-item>
      <el-form-item label="保质期（天）" :label-width="100">
        <el-input v-model="insertform.shelflifeDay" clearable />
      </el-form-item>
      <el-form-item label="生产许可证号" :label-width="100">
        <el-input v-model="insertform.productionlicense" clearable />
      </el-form-item>
      <el-form-item label="生产企业" :label-width="100">
        <el-input v-model="insertform.productionCompany" clearable />
      </el-form-item>
      <el-form-item label="封面图" :label-width="100">
        <el-upload v-model="insertform.coverimage" action="#" list-type="picture-card" :auto-upload="false" @change="handfilechange">
    <el-icon><Plus /></el-icon>

    <template #file="{ file }">
      <div>
        <img  class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleDownload(file)"
          >
            <el-icon><Download /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <el-icon><Delete /></el-icon>
          </span>
        </span>
      </div>
    </template>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="inserttrace">
          新增
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--修改-->
  <el-dialog v-model="dialoguptFormVisible" title="修改溯源" width="500">
    <el-form :model="uptform">
      <el-form-item label="商品名称" :label-width="100">
        <el-select
      v-model="uptform.goodsId"
      placeholder="请选择"
    >
      <el-option
        v-for="item in goodsData"
        :key="item.goodsId"
        :label="item.goodsName"
        :value="item.goodsId"
      />
    </el-select>
      </el-form-item>
      <el-form-item label="生产批次" :label-width="100">
        <el-input v-model="uptform.productionbatches" clearable />
      </el-form-item>
      <el-form-item label="保质期（天）" :label-width="100">
        <el-input v-model="uptform.shelflifeDay" clearable />
      </el-form-item>
      <el-form-item label="生产许可证号" :label-width="100">
        <el-input v-model="uptform.productionlicense" clearable />
      </el-form-item>
      <el-form-item label="生产企业" :label-width="100">
        <el-input v-model="uptform.productionCompany" clearable />
      </el-form-item>
      <el-form-item label="封面图" :label-width="100">
        <el-upload v-model="uptform.coverimage" action="#" list-type="picture-card" :auto-upload="false" @change="handfilechange">
    <el-icon><Plus /></el-icon>

    <template #file="{ file }">
      <div>
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleDownload(file)"
          >
            <el-icon><Download /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <el-icon><Delete /></el-icon>
          </span>
        </span>
      </div>
    </template>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="updatetrace">
          修改
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--分页-->
  <table>
    <tr>
      <td>
        <el-pagination
      v-model:current-page="page.PageIndex"
      v-model:page-size="page.PageSize"
      :page-sizes="[1, 2, 3, 4]"
      :background="true"
      layout="slot, sizes"
      :total="page.totalcount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    当前第{{page.PageIndex }}页
    每页显示{{ page.PageSize }}条
    共{{ page.totalcount }}条
    共{{ page.totalpage }}页
    </el-pagination>
      </td>
      <td>
        <el-pagination
      v-model:current-page="page.PageIndex"
      v-model:page-size="page.PageSize"
      :page-sizes="[1, 2, 3, 4]"
      :background="true"
      layout="slot, prev, pager, next"
      :total="page.totalcount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页"
    >
    <el-button type="primary"  @click="handleCurrentChange(1)" :disabled="page.PageIndex==1">首页</el-button>
    </el-pagination>
      </td>
      <td>
        <el-pagination
      v-model:current-page="page.PageIndex"
      v-model:page-size="page.PageSize"
      :page-sizes="[1, 2, 3, 4]"
      :background="true"
      layout="slot, jumper"
      :total="page.totalcount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    <el-button type="primary"  @click="handleCurrentChange(page.totalpage)" :disabled="page.PageIndex==page.totalpage">首页</el-button>
    </el-pagination>
      </td>
    </tr>
  </table>
  
</template>

<script setup lang="ts">
import { ref,reactive,onMounted } from 'vue'
import { Menu as IconMenu, Message, Setting,Document,Shop,Search,Delete,Plus,RefreshRight,Filter } from '@element-plus/icons-vue'
import { UserFilled } from '@element-plus/icons-vue'
import { ElMessage, TableInstance,ElMessageBox } from 'element-plus'
import axios from 'axios'
import {useRouter} from 'vue-router'
const router=useRouter()
//处理文件变化事件
const handfilechange=(file:UploadFile)=>{
      if(file.status=='ready')
      {
        UploadFiles(file);
      }
}
//file.url
const fromDatas=reactive({
  Photo:''
})
//图片上传
const UploadFiles=async(file:UploadFile)=>{
  const formData=new FormData()
  formData.append('file',file.raw);//使用file.raw获取原始文件
  const response=await axios.post('http://localhost:5072/api/Upload/UploadFile/UploadFile',formData,{
    headers:{
      'content-Type':'mutipart/form-data'
    }
  })
  //处理上传后的逻辑
  if(response.status==200)
  {
    ElMessage.success('上传成功')
    fromDatas.Photo+=response.data+`,`;
    console.log(fromDatas.Photo)
  }
  else{
    ElMessage.error('上传失败')
  }
}



interface TraceList{
        "trId":number,
        "goodsId":number,
        "productionbatches":string,
        "shelflifeDay":number,
        "productionlicense":string,
        "productionCompany":string,
        "coverimage":string,
        "goodsName":string
}

const tableData = ref<TraceList[]>([])
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<TraceList[]>([])
const handleSelectionChange = (val:any) => {
  multipleSelection.value = val
}
//分页参数
const page=reactive({
    PageIndex:1,
    PageSize:2,
    totalcount:0,
    totalpage:0
})
//查询参数
const serch=reactive({
  GoodsName:'',
  Productionbatches:'',
  ShelflifeDay:0,
  Productionlicense:'',
  ProductionCompany:''
})
//类似（jquery）的就绪函数
onMounted(()=>{
    gettrace()
    getgoodsllist()
})
//显示方法
const gettrace=()=>{
    axios.get('http://localhost:5072/api/TranceShuoYuan/DisplayTrance',{
        params:{
            PageIndex:page.PageIndex,
            PageSize:page.PageSize,
            GoodsName:serch.GoodsName,
            Productionbatches:serch.Productionbatches,
            ShelflifeDay:serch.ShelflifeDay,
            Productionlicense:serch.Productionlicense,
            ProductionCompany:serch.ProductionCompany
        }
    })
    .then(res=>{
        console.log(res)
        tableData.value=res.data.data.list
        page.totalcount=res.data.data.totalCount
        page.totalpage=res.data.data.totalPage
    })
    .catch(err=>{
        console.log(err)
    })
}

interface goodsss{
      "goodsId":number,
      "goodsName":string
}

const goodsData=ref<goodsss[]>([])
//显示商品下拉
const getgoodsllist=()=>{
  axios.get('http://localhost:5072/api/Goods/DisplayGoods')
  .then(res=>{
        console.log(res)
        goodsData.value=res.data.data
    })
    .catch(err=>{
        console.log(err)
    })
}


//打开新增按钮
const dialoginsertFormVisible=ref(false)
const AddTrace=()=>{
  dialoginsertFormVisible.value=true
  gettrace()
}
interface insertform{
  "goodsId":number,
  "productionbatches":string,
  "shelflifeDay":number,
  "productionlicense":string,
  "productionCompany":string,
  "coverimage":string
}

const insertform=reactive({
  "goodsId":'',
  "productionbatches": "",
  "shelflifeDay":'',
  "productionlicense": "",
  "productionCompany": "",
  "coverimage":""
})
//新增
const inserttrace=()=>{
  if(insertform.goodsId=='')
  {
    ElMessageBox('商品名称不能为空')
    return
  }
  if(insertform.productionbatches=='')
  {
    ElMessageBox('生产批次不能为空')
    return
  }
  if(insertform.shelflifeDay=='')
  {
    ElMessageBox('保质期（天）不能为空')
    return
  }
  if(insertform.productionlicense=='')
  {
    ElMessageBox('生产许可证号不能为空')
    return
  }
  if(insertform.productionCompany=='')
  {
    ElMessageBox('生产企业不能为空')
    return
  }
  axios.post('http://localhost:5044/api/TranceShuoYuan/AddTrance',insertform)
  .then(res=>{
    console.log(res)
    if(res.data.isSuc)
    {
      ElMessage.success('新增成功')
      dialoginsertFormVisible.value=false
      gettrace()
    }
    else{
      ElMessage.error(res.data.msg)
      return
    }
  })
  .catch(err=>{
    console.log(err)
  })
}
import type { UploadFile } from 'element-plus'

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

const handleRemove = (file: UploadFile) => {
  console.log(file)
}

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}

const handleDownload = (file: UploadFile) => {
  console.log(file)
}
//单删
const handdeltraceId=(trId:number)=>{
  ElMessageBox.confirm(
    '确认要删除该溯源吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(()=>{
    axios.delete('http://localhost:5044/api/TranceShuoYuan/DelTrance?TrId='+trId)
  .then(res=>{
    console.log(res)
    if(res.data.isSuc)
    {
      ElMessage.success('删除成功')
      return
    }
    else{
      ElMessage.success(res.data.msg)
      return
    }
  })
  })
  .catch(err=>{
    console.log(err)
  })
}

//打开修改按钮
const dialoguptFormVisible=ref(false)
const handupdatetraceable=(trId:number)=>{
  dialoguptFormVisible.value=true
  gettrace()
  axios.get('http://localhost:5072/api/TranceShuoYuan/BackTranceById?TrId='+trId)
  .then(res=>{
    console.log(res)
    uptform.trId=res.data.data.trId
    uptform.goodsId=res.data.data.goodsId
    uptform.productionbatches=res.data.data.productionbatches
    uptform.shelflifeDay=res.data.data.shelflifeDay
    uptform.productionlicense=res.data.data.productionlicense
    uptform.productionCompany=res.data.data.productionCompany
    uptform.coverimage=res.data.data.coverimage
  })
  .catch(err=>{
    console.log(err)
  })
}
interface uptform{
  "trId":number,
  "goodsId":number,
  "productionbatches":string,
  "shelflifeDay":number,
  "productionlicense":string,
  "productionCompany":string,
  "coverimage":string
}

const uptform=reactive({
  "trId":'',
  "goodsId":'',
  "productionbatches": "",
  "shelflifeDay":'',
  "productionlicense": "",
  "productionCompany": "",
  "coverimage":""
})
//修改
const updatetrace=()=>{
  axios.put('http://localhost:5044/api/TranceShuoYuan/UpdateTrance',uptform)
  .then(res=>{
    console.log(res)
    if(res.data.isSuc)
    {
      ElMessage.success('修改成功')
      dialoguptFormVisible.value=false
      gettrace()
    }
    else{
      ElMessage.error(res.data.msg)
      return
    }
  })
  .catch(err=>{
    console.log(err)
  })
}

//分页事件
const handleSizeChange = (val: number) => {
  page.PageSize=val;
  gettrace()
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  page.PageIndex=val;
  gettrace();
  console.log(`current page: ${val}`)
}
//跳转到详情页
const handMing=(trId:number)=>{
  router.push({
    path:'/GetCultivationList',
    query:{
      trId:trId
    }
  })
}
</script>

<style scoped>
.layout-container-demo .el-header {
  position: relative;
  background-color: var(--el-color-primary-light-7);
  color: var(--el-text-color-primary);
}
.layout-container-demo .el-aside {
  color: var(--el-text-color-primary);
  background: var(--el-color-primary-light-8);
}
.layout-container-demo .el-menu {
  border-right: none;
}
.layout-container-demo .el-main {
  padding: 0;
}
.layout-container-demo .toolbar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  right: 20px;
}
.demo-type {
  display: flex;
}
</style>